//
//  JZOperation.m
//  tf02
//
//  Created by F7686324 on 2017/1/7.
//  Copyright © 2017年 Jim. All rights reserved.
//

#import "PYNetworking.h"

#import "AFNetworking.h"

#import "NSDictionary+JSONString.h"

//#import "PYLogin.h"

#import "PYLoginViewController.h"

@interface PYNetworking ()

@property (nonatomic, strong, readwrite) NSDictionary *parameters;
@property (nonatomic, copy, readwrite) NSString *url;
@property (nonatomic, assign, readwrite) JZRequestType requestType;

- (void)private_successWithTask:(NSURLSessionDataTask *)task
                 responseObject:(id)responseObject
                        success:(void (^)(NSURLSessionDataTask *task, id responseObject))success;

- (void)private_failureWithTask:(NSURLSessionDataTask *)task
                          error:(NSError *)error
                        failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
@end

@implementation PYNetworking

+ (AFHTTPSessionManager *)manager
{
    static AFHTTPSessionManager *manager = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        manager = [AFHTTPSessionManager manager];
        
    });
    
    return manager;
}

/**
 * AF网络请求
 */
+ (instancetype)networkingWithURLString:(NSString *)URLString
                              parameters:(id)parameters
                           requestType:(JZRequestType)requestType
                               success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                               failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    PYNetworking *networking = [[PYNetworking alloc] init];
    
    if (![URLString isValidString]) {
        
        NSLog(@"URL为空");
        return networking;
    }
    
    networking.url = URLString;
    networking.parameters = parameters;
    networking.requestType = requestType;
    NSLog(@"\n AF网络请求参数列表:%@\n\n 接口名: %@\n\n", [parameters isKindOfClass:[NSDictionary class]] ? [parameters JSONString] : parameters, URLString);
    
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [PYNetworking manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    // 2.申明返回的结果是JSON类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSString *token = [NSString valueByKey:kToken];

    if (token) {
        
        NSLog(@"token = %@", token);
        
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    }
    
    // 3.如果接受类型不一致请替换
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                         @"application/json",
//                                                         @"text/json",
//                                                         @"text/javascript",
//                                                         @"text/html",
                                                         @"text/plain",
//                                                         @"text/xml",
                                                         nil];
    
    // 4.请求超时，时间设置
    manager.requestSerializer.timeoutInterval = 30;
    
    // 5.选择请求方式 GET 或 POST
    switch (requestType) {
        case PY_GET:
        {
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                
                NSLog(@"%@_responseObject = %@", URLString, [responseObject JSONString]);

                [networking private_successWithTask:task responseObject:responseObject success:success];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [networking private_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
            
        case PY_POST:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                
                NSLog(@"%@_responseObject = %@", URLString, [responseObject JSONString]);

                [networking private_successWithTask:task responseObject:responseObject success:success];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
                [networking private_failureWithTask:task error:error failure:failure];
                
            }];
        }
            break;
        
        case PY_DELETE:
        {
            [manager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSLog(@"%@_responseObject = %@", URLString, [responseObject JSONString]);

                [networking private_successWithTask:task responseObject:responseObject success:success];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               
                [networking private_failureWithTask:task error:error failure:failure];
                
            }];
        }
            break;
            
        case PY_PUT:
        {
            [manager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSLog(@"%@_responseObject = %@", URLString, [responseObject JSONString]);

                [networking private_successWithTask:task responseObject:responseObject success:success];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [networking private_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
        default:
            break;
    }
    return networking;
}

- (void)private_successWithTask:(NSURLSessionDataTask *)task
         responseObject:(id)responseObject
                success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
{
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        
        if ([responseObject[@"code"] integerValue] == -1) {

            if ([[UIApplication sharedApplication].keyWindow.rootViewController isKindOfClass:[PYNavigationController class]]) {
                
                PYNavigationController *navi = (PYNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                if ([navi.visibleViewController isKindOfClass:[PYLoginViewController class]]) {
                    
                    return;
                }
            }
            
            [@"" storeValueByKey:kLoginType];
            
            [@"" storeValueByKey:kCurrentUserPassword];
            
            [@"" storeValueByKey:kToken];
            
            [@"" storeValueByKey:kCurrentUserID];
            
            PYLoginViewController *loginVC = [[PYLoginViewController alloc] init];
            
            PYNavigationController *navi = [[PYNavigationController alloc] initWithRootViewController:loginVC];
            
            navi.navigationBar.backgroundColor = nil;
            
            navi.navigationBar.barTintColor = nil;
            
            navi.navigationBar.translucent = YES;
            
            navi.navigationBar.barStyle = UIBarStyleBlack;
            
            [UIApplication sharedApplication].keyWindow.rootViewController = navi;
            
            [MBProgressHUD showText:@"您的账号已在其他地方登陆，请重新登录" toView:nil];
            
            return;
        }
    }
    success(task, responseObject);
    
    success = nil;
}

- (void)private_failureWithTask:(NSURLSessionDataTask *)task
                  error:(NSError *)error
                failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{    
    NSLog(@"\n 请求失败:%@\n\n",error);
    
    if (error.code != -999) {
    
        failure(task, error);

    }
    
    failure = nil;
}


+ (void)cancelAFHTTPRequest
{
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [PYNetworking manager];
    NSArray *dataTasks = [manager dataTasks];
    for (NSURLSessionDataTask *dataTask in dataTasks) {
        [dataTask cancel];
    }

}

@end
